package com.zh.mp.demo.config;

import com.zh.mp.demo.thread.MyThreadFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.StopWatch;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

//@Slf4j
//@Configuration
//@EnableScheduling
public class ScheduledConfig {
    protected SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");

    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.initialize();
        threadPoolTaskScheduler.setPoolSize(20);
        threadPoolTaskScheduler.setThreadNamePrefix("taskExecutor-");
        threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true);
        threadPoolTaskScheduler.setAwaitTerminationSeconds(60);
//        String cron = "0/10 * * * * ? ";
//        threadPoolTaskScheduler.schedule((Runnable) () -> {
//            try {
//                // 触发进行记录日志
//                StopWatch watch = new StopWatch();
//                watch.start();
//                //log.info(watch.toString());
//                watch.stop();
//                log.info(String.format("时间:%s",ft.format(new Date( ))));
//                //log.info(String.format("调度器rpc调用完成,耗时:%s", watch.getLastTaskTimeMillis()));
//            } catch (Exception ex) {
//                log.error(String.format("调度器出现异常:%s", ex.getMessage()));
//            }
//        }, new CronTrigger(cron));

        return threadPoolTaskScheduler;
    }

    @Bean
    public ScheduledExecutorService scheduledExecutorService() {
        MyThreadFactory threadFactory = new MyThreadFactory();
        ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(10, threadFactory);
//        scheduledExecutorService.scheduleAtFixedRate((Runnable) () -> {
//            try {
//                log.info(String.format("时间:%s",ft.parse("2021-01-01 00:00:00")));
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//        }, 3000, 3000, TimeUnit.MILLISECONDS);
//        scheduledExecutorService.scheduleWithFixedDelay((Runnable) () -> {
//            log.info(String.format("时间:%s",ft.format(new Date( ))));
//        }, 3000, 3000, TimeUnit.MILLISECONDS);

        return scheduledExecutorService;
    }
}
